<template>
  <el-dialog
    v-model="show"
    width="42%"
    custom-class="form_dialog"
    append-to-body
    :close-on-click-modal="false"
    :before-close="closeDialog"
    v-dialog-drag
  >
    <template #header>
      <div class="manage_tit">
        <div class="line"></div>
        <p>主体信息编辑</p>
      </div>
    </template>
    <el-form
      ref="enterpriseFormRef"
      :model="enterpriseForm"
      :rules="enterpriseRules"
      :hide-required-asterisk="true"
      label-position="left"
      label-width="150px"
    >
      <div class="form_item">
        <el-form-item label="企业类型" prop="enterpriseType">
          <el-radio-group v-model="enterpriseForm.enterpriseType">
            <el-radio
              v-for="dict in dict?.type?.enterprise_type"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input
            clearable
            class="input_style"
            v-model="enterpriseForm.enterpriseName"
            placeholder="请输入企业名称"
          />
          <p class="form_tips">
            需与当地政府颁发的营业许可证书或企业注册证上的企业名称完全一致，信息审核成功后，企业名称不可修改。
          </p>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="businessLicenseNum">
          <el-input
            clearable
            class="input_style license_num"
            v-model="enterpriseForm.businessLicenseNum"
            placeholder="请输入统一社会信用代码"
            disabled
          ></el-input>
          <!-- <p class="form_tips">
            请输入15位营业执照注册号或18位的统一社会信用代码。
          </p> -->
        </el-form-item>
        <el-form-item label="工商营业执照" prop="businessImg" class="business_img">
          <p class="form_tips" style="margin-bottom: 8px">
            请上传<span class="blue">最新的营业执照</span>，格式要求：支持 .jpg .jpeg .bmp .gif
            .png格式照片，大小不超过10M。
          </p>
          <upload-img
            v-model="enterpriseForm.businessImg"
            :files="enterpriseForm.businessImg"
            :limit="1"
            @change="changeBusinessImg"
            :size="10"
            ref="businessImgRef"
          />
        </el-form-item>
      </div>
      <p class="form_tit">
        <i>*</i>
        <span>认证联系人信息</span>
      </p>
      <div class="form_item">
        <el-form-item label="联系人姓名" prop="contactPerson">
          <el-input
            clearable
            class="input_style"
            v-model="enterpriseForm.contactPerson"
            placeholder="请输入联系人姓名"
          />
        </el-form-item>
        <el-form-item label="联系人身份证号" prop="contactId">
          <el-input
            clearable
            class="input_style"
            v-model="enterpriseForm.contactId"
            placeholder="请输入联系人身份证号"
          />
        </el-form-item>
        <el-form-item label="身份证照片">
          <p class="form_tips" style="margin-bottom: 8px">
            请上传联系人身份证原件。保证证件边缘完整、文字清晰、光线均匀。
          </p>
          <div class="idCardList">
            <upload-img
              v-model="enterpriseForm.contactImg"
              :files="enterpriseForm.contactImg"
              :limit="2"
              :size="10"
              @change="getCardImgFront"
              ref="contactImgFrontRef"
            >
              <template #upload-button>
                <div class="card_upload">
                  <p class="upload_add">+</p>
                  <p class="upload_txt">上传图片</p>
                </div>
              </template>
            </upload-img>
          </div>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input
            clearable
            class="input_style"
            v-model="enterpriseForm.contactPhone"
            placeholder="请输入联系人电话"
          >
          </el-input>
        </el-form-item>
      </div>
      <p class="form_tit">
        <i>*</i>
        <span>对公账户信息</span>
      </p>
      <div class="form_item">
        <el-form-item label="开户名称" prop="accountName">
          <el-input
            clearable
            class="input_style"
            v-model="enterpriseForm.accountName"
            placeholder="请输入开户名称"
          />
        </el-form-item>
        <el-form-item label="开户银行" prop="accountBank">
          <el-input
            clearable
            class="input_style"
            v-model="enterpriseForm.accountBank"
            placeholder="请输入开户银行"
          />
        </el-form-item>
        <el-form-item label="银行账号" prop="accountBankNumber">
          <el-input
            clearable
            class="input_style"
            v-model="enterpriseForm.accountBankNumber"
            placeholder="请输入银行账号"
          />
        </el-form-item>
      </div>
      <div class="contract_form">
        <p class="form_tit">
          <i>*</i>
          <span>上传合同</span>
        </p>
        <div class="form_item">
          <el-form-item label-width="0" prop="pactImg">
            <p class="align_center">
              请拍照上传加盖公章的合同原件或电子合同
              <span
                class="align_center"
                @click="downloadFile"
                style="margin-left: 10px; color: #0988fb; cursor: pointer"
                v-if="enterpriseForm.contractFile.length > 0"
                ><img src="@/assets/images/icon/download_icon.png" />下载合同</span
              >
            </p>
            <upload-img
              v-model="enterpriseForm.contractFile"
              :files="enterpriseForm.contractFile"
              :limit="1"
              :accept="'.pdf'"
              :listType="'text'"
              :size="10"
              fileType="file"
              @change="getContractFile"
              ref="contractFileRef"
              class="contract_file"
            />
            <div class="upload_contract">
              <upload-img
                :limit="100"
                :size="10"
                @change="getContractImg"
                v-model="enterpriseForm.contractImg"
                :files="enterpriseForm.contractImg"
                ref="contractImgRef"
              >
                <template #upload-button>
                  <div class="upload_btn">
                    <p class="upload_add">+</p>
                    <p class="upload_txt">上传图片</p>
                  </div>
                </template>
              </upload-img>
            </div>
          </el-form-item>
        </div>
      </div>
      <el-form-item label="上级公司" prop="deptId">
        <el-cascader
          filterable
          clearable
          :options="deptList"
          :props="{ checkStrictly: true }"
          v-model="enterpriseForm.deptId"
        ></el-cascader>
      </el-form-item>
      <div class="form_btn">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button class="default_btn" @click="closeDialog">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import uploadImg from '@/components/Upload/uploadImg.vue'
import { debounce } from 'lodash'
import { createStadium } from '@/api/stadium/stadium'
import { deptTreeSelect } from '@/api/system/user'
import { ElMessage, ElMessageBox, type FormInstance, type UploadFile } from 'element-plus'
import type { CascaderOption } from 'element-plus'

interface DictType {
  type: {
    enterprise_type: Array<{ value: string; label: string }>
  }
}

interface FormData {
  id: null | string
  enterpriseType: string
  enterpriseName: string
  businessLicenseNum: string
  businessImg: string
  contactPerson: string
  contactPhone: string
  contactId: string
  contactImg: string
  accountName: string
  accountBank: string
  accountBankNumber: string
  pactImg: string
  pactName: string | undefined
  contractFile: Array<{ name: string; url: string }>
  contractImg: Array<{ name: string; url: string }>
  deptId: string | string[] | null
  dataFlag: null | string
  [key: string]: any
}

interface DeptItem {
  id: string
  label: string
  disabled?: boolean
  children?: DeptItem[]
}

const props = withDefaults(
  defineProps<{
    // show: boolean
    formData: FormData
  }>(),
  {
    // show: false,
    formData: () => ({
      id: null,
      enterpriseType: '',
      enterpriseName: '',
      businessLicenseNum: '',
      businessImg: '',
      contactPerson: '',
      contactPhone: '',
      contactId: '',
      contactImg: '',
      accountName: '',
      accountBank: '',
      accountBankNumber: '',
      pactImg: '',
      pactName: undefined,
      contractFile: [],
      contractImg: [],
      deptId: null,
      dataFlag: null,
    }),
  },
)

const show = defineModel('show', { default: false })
const emit = defineEmits<{
  (e: 'close', value?: number): void
}>()

// 定义字典数据
const dict = ref<DictType>({
  type: {
    enterprise_type: [],
  },
})

// 表单引用
const enterpriseFormRef = ref<FormInstance>()
const businessImgRef = ref<InstanceType<typeof uploadImg>>()
const contactImgFrontRef = ref<InstanceType<typeof uploadImg>>()
const contractFileRef = ref<InstanceType<typeof uploadImg>>()
const contractImgRef = ref<InstanceType<typeof uploadImg>>()

// 表单数据
const enterpriseForm = ref<FormData>({ ...props.formData })

// 表单验证规则
const enterpriseRules = ref({
  enterpriseType: [{ required: true, message: '请选择企业类型', trigger: 'change' }],
  enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  businessLicenseNum: [
    {
      required: true,
      message: '请输入统一社会信用代码',
      trigger: 'blur',
    },
  ],
  businessImg: [
    {
      required: true,
      message: '请上传工商营业执照',
      trigger: 'change',
    },
  ],
  contactPerson: [
    {
      required: true,
      message: '请输入联系人姓名',
      trigger: 'blur',
    },
  ],
  contactId: [
    {
      required: true,
      message: '请输入联系人身份证号',
      trigger: 'blur',
    },
  ],
  contactPhone: [
    {
      required: true,
      message: '请输入联系人电话',
      trigger: 'blur',
    },
  ],
  accountName: [
    {
      required: true,
      message: '请输入开户名称',
      trigger: 'blur',
    },
  ],
  accountBank: [
    {
      required: true,
      message: '请输入开户银行',
      trigger: 'blur',
    },
  ],
  accountBankNumber: [
    {
      required: true,
      message: '请输入银行账号',
      trigger: 'blur',
    },
  ],
  pactImg: [
    {
      required: true,
      message: '请上传合同',
      trigger: 'change',
    },
  ],
  deptId: [{ required: true, message: '请选择归属公司', trigger: 'change' }],
})

const deptList = ref<CascaderOption[]>([])

// 保存
const handleSubmit = debounce(
  async () => {
    try {
      let pactImg = ''
      if (enterpriseForm.value.contractFile.length > 0) {
        enterpriseForm.value.pactName = enterpriseForm.value.contractFile[0]?.name || ''
        pactImg = enterpriseForm.value.contractFile.map((item) => item.url).join(',') || ''
      }
      if (enterpriseForm.value.contractImg.length > 0) {
        pactImg =
          (pactImg != '' ? pactImg + ',' : '') +
          enterpriseForm.value.contractImg.map((item) => item.url).join(',')
      }
      enterpriseForm.value.pactImg = pactImg
      const enterpriseParams = JSON.parse(JSON.stringify(enterpriseForm.value))
      if (enterpriseParams.deptId != null && Array.isArray(enterpriseParams.deptId)) {
        enterpriseParams.deptId = enterpriseParams.deptId.slice(-1)[0]
      }
      if (!enterpriseFormRef.value) return
      const valid = await enterpriseFormRef.value.validate()
      if (valid) {
        const res = await createStadium(enterpriseParams)
        ElMessage.success(res.msg)
        emit('close', 1)
      }
    } catch (e) {
      ElMessage.error((e as any) || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 关闭弹窗
const closeDialog = () => {
  emit('close')
}

/** 查询部门列表 */
const getDeptList = () => {
  deptTreeSelect().then((response) => {
    deptList.value = formatToCascaderData(response.data)
  })
}

// 数据处理为兼容cascader数据格式
const formatToCascaderData = (rawData: DeptItem[]): CascaderOption[] => {
  const processNode = (node: DeptItem): CascaderOption | null => {
    if (!node) return null

    const processed: CascaderOption = {
      value: node.id,
      label: node.label,
      disabled: node.disabled,
    }

    if (node.children && node.children.length > 0) {
      const filteredChildren = node.children
        .map(processNode)
        .filter((child): child is CascaderOption => child !== null)
      if (filteredChildren.length > 0) {
        processed.children = filteredChildren
      }
    }

    return processed
  }

  return rawData.map(processNode).filter((node): node is CascaderOption => node !== null)
}

// 获取工商营业执照
const changeBusinessImg = (data: UploadFile[]) => {
  enterpriseForm.value.businessImg = data.map((item) => item.url || '').join(',')
  if (enterpriseFormRef.value) {
    enterpriseFormRef.value.clearValidate('businessImg')
  }
}

// 获取合同文件
const getContractFile = (data: UploadFile[]) => {
  enterpriseForm.value.contractFile = data.map((item) => ({
    name: item.name || '',
    url: item.url || '',
  }))
  if (enterpriseFormRef.value) {
    enterpriseFormRef.value.clearValidate('pactImg')
  }
}

// 获取合同图片
const getContractImg = (data: UploadFile[]) => {
  enterpriseForm.value.contractImg = data.map((item) => ({
    name: item.name || '已上传图片',
    url: item.url || '',
  }))
  enterpriseFormRef.value?.clearValidate('pactImg')
}

// 获取身份证正面图片
const getCardImgFront = (data: UploadFile[]) => {
  enterpriseForm.value.contactImg = data.map((item) => item.url || '').join(',')
  if (enterpriseFormRef.value) {
    enterpriseFormRef.value.clearValidate('contactImg')
  }
}

// 处理企业认证信息的回显
const handleEnterpriseData = (enterpriseData: FormData) => {
  // 通过更新表单数据来触发uploadImg组件的更新，移除对组件内部属性的直接访问

  const imgBusiness = enterpriseForm.value.businessImg.split(',').filter(Boolean)
  enterpriseForm.value.businessImg = imgBusiness.join(',')

  const imgFront = enterpriseForm.value.contactImg.split(',').filter(Boolean)
  enterpriseForm.value.contactImg = imgFront.join(',')

  const pactImgArr = enterpriseData?.pactImg?.split(',') || []
  if (enterpriseData.pactName && enterpriseData.pactName.trim() !== '') {
    const files = pactImgArr[0]
    enterpriseForm.value.contractFile = [
      {
        name: enterpriseData.pactName || '合同文件',
        url: files || '',
      },
    ]
    enterpriseForm.value.contractImg = pactImgArr
      .slice(1)
      .filter(Boolean)
      .map((url) => ({
        name: '已上传图片',
        url,
      }))
  } else {
    // 当没有文件名信息时，使用默认名称
    enterpriseForm.value.contractFile = []
    enterpriseForm.value.contractImg = pactImgArr.filter(Boolean).map((url) => ({
      name: '已上传图片',
      url,
    }))
  }

  if (enterpriseForm.value.deptId && typeof enterpriseForm.value.deptId === 'string') {
    enterpriseForm.value.deptId = enterpriseForm.value.deptId.split(',')
  }
}

// 合同下载
const downloadFile = async () => {
  const file = enterpriseForm.value.contractFile?.[0]
  if (!file?.url || !file.name) return

  try {
    const response = await fetch(file.url)
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)

    const blob = await response.blob()
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = file.name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('下载文件时发生错误:', error)
    ElMessage.error('下载失败，请稍后重试')
  }
}

watch(
  () => show.value,
  (val) => {
    if (val) {
      enterpriseForm.value = JSON.parse(JSON.stringify(props.formData))
      nextTick(() => {
        handleEnterpriseData(enterpriseForm.value)
      })
      getDeptList()
    }
  },
  {
    deep: true,
  },
)
</script>

<style lang="scss" scoped>
:deep(.el-form) {
  padding-right: 72px;
  // .el-select,
  // .el-cascader {
  //   width: 100%;
  // }
  .form_tit {
    font-size: 14px;
    line-height: 21px;
    margin: 25px 0 15px;
    i {
      color: #d43030;
      margin-right: 2px;
    }
  }
  .el-form-item .el-form-item {
    margin-bottom: 10px;
  }
  .el-form-item__label {
    font-weight: normal;
    color: #383838;
  }
  .idCardList {
    display: flex;
    .el-upload-list--picture-card .el-upload-list__item {
      width: 156px;
      height: 99px;
    }
  }
  .card_upload {
    width: 156px;
    height: 99px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-right: 24px;
    p {
      font-size: 14px;
      color: #a6a6a6;
      line-height: 21px;
      &.upload_add {
        font-size: 48px;
        margin-top: 24px;
      }
      &.upload_txt {
        margin-top: 10px;
      }
    }
  }
  .contract_form {
    display: flex;
    .form_tit {
      width: 150px;
      margin-top: 11px;
    }
    .form_item {
      margin-top: 11px;
      p {
        font-size: 12px;
        color: #808080;
        line-height: 18px;
        margin-bottom: 9px;
      }
    }
  }
  .form_tips {
    line-height: normal;
    margin-top: 10px;
  }
  .business_img {
    .el-upload-list--picture-card .el-upload-list__item {
      width: 150px;
      height: 110px;
    }
  }
  .upload_contract {
    margin-top: 10px;
  }
  .upload_btn {
    width: 110px;
    height: 110px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    .upload_add {
      font-size: 48px !important;
      margin-top: 30px;
    }
    .upload_txt {
      margin-top: 10px;
    }
  }
  .align_center {
    .el-input {
      flex: 1;
    }
    p {
      margin-left: 19px;
      font-size: 14px;
      color: #d43030;
    }
  }
  .form_btn {
    display: flex;
    justify-content: center;
    .el-button {
      width: 90px;
      height: 38px;
      border-radius: 8px;
      & + .el-button {
        margin-left: 40px;
      }
    }
  }
}
</style>
